<?php
namespace control;
/*
*采购付款统计类
*/

class canteenPayClass extends adIndexClass
{
    private const page = 'canteenPay';
    private const title = '采购付款统计';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'hall'          => [
                        'name'  => '食堂名称',
                        'width' => 300,
                    ],
                    'supplierName' => [
                        'name'  => "供应商名称",
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'buyMoney'  => [
                        'name'  => '采购金额(' . static::$unit . ')',
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'payMoney'         => [
                        'name'  => '已付款金额(' . static::$unit . ')',
                        'text'  => componentClass::tipComponent('已拨付状态的'),
                        'width' => 300,
                    ],
                    'residue'          => [
                        'name'  => '剩余未付金额(' . static::$unit . ')',
                        'width' => 300,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "食堂名称" => selectMultiple(array("name" => "hallId", 'table' => "dining_hall", 'sqlId' => 'id', 'sqlField' => 'name', 'class' => 'width200')),
                    "供应商名称"     => text(array("name" => "supplierName")),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        //返回
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array();
        //全等查询数组
        $equal = array(
            "c.state" => '已复核',
            "c.hallId" => $this->post('hallId'),//食堂
            "b.supplierName" => $this->post('supplierName'),
        );
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'buyMoney',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . " and 1=1";
        $page = $this->page(array(
            'field' => "c.hallId,b.supplierName,ifnull(sum(any_value(b.price) * any_value(b.num)),0) as buyMoney",
            "table" => "canteen_detail as b join canteen as c on b.orderId = c.id",
            "where" => $where . " group by c.hallId,b.supplierName",
            "order" => $orderBy['orderBy']
        ));
        static::rSet(self::$stid.self::page. 'sql', $page['fullSql'], 3600 * 5); // 设置redis
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array("");
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&hallId=" . $array['hallId'] . "&supplierName={$array['supplierName']}')"),
            );
            $liButton[] = $this->dominate($dominate);
            $payMoney = find(array('table'=>'payment','where'=>"targetId = '$array[supplierName]' and hallId = '$array[hallId]' and state = '已通过' and isPay = 1",'sum'=>"money"));
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "hall":
                        $hall = query('dining_hall', "id = '$array[hallId]'");
                        $row[] = $hall['name'];
                        break;
                    case "buyMoney":
                        $row[] = round($array['buyMoney'],2);
                        break;
                    case "payMoney":
                        $row[] = $payMoney;
                        break;
                    case "residue":
                        $row[] = $array['buyMoney'] - $payMoney;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find(array(
            'table' => "canteen_detail as b join canteen as c on b.orderId = c.id",
            'single' => $where,
            'field' => "ifnull(sum(b.price * b.num),0) as buyMoney"
        ));
        $payMoney = find(array(
            'table'=>'payment',
            'where'=>"targetId in (select b.supplierName from canteen_detail as b join canteen as c on b.orderId = c.id where 1=1 {$where}) and hallId in (select c.hallId from canteen_detail as b join canteen as c on b.orderId = c.id where 1=1 {$where}) and state = '已通过' and isPay = 1",
            'sum'=>"money"
        ));
        $total    = [
            'buyMoney'        => self::lostZero($totalQuery['buyMoney']),
            'payMoney'        => self::lostZero($payMoney),
            'residue'        => $totalQuery['buyMoney'] - $payMoney,
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /*详情页*/
    public function detail()
    {
        $supplierName = $this->get('supplierName');
        $hallId = $this->get('hallId');
        if (empty($hallId) || empty($supplierName)) {
            $html = '未找此详情';
        } else {
            //菜单
            $data = array(
                "id" => '',
            );
            $purchaseTr[] = ['日期', '单号', '类别', '产品名称', '数量', '单价('.static::$unit.')', '金额('.static::$unit.')', '备注'];
            $result = find(array('table' => 'canteen_detail as a join canteen as b on a.orderId = b.id', 'field'=>"a.*,b.orderNo,b.purchaseDate",'where' => "b.hallId = '$hallId' and a.supplierName = '$supplierName'order by a.list asc"));
            foreach ($result['array'] as $array) {
                $purchaseTr[] = [
                    $array['purchaseDate'],
                    $array['orderNo'],
                    $array['type'],
                    $array['materialName'],
                    $array['num'],
                    $array['price'],
                    round($array['num']*$array['price']),
                    $array['text'],
                ];
            }
            $payTr[] = ['日期', '单号', '付款金额('.static::$unit.')', '付款人','备注'];
            $result = find(array('table' => 'payment', 'where' => "targetId = '$supplierName' and hallId = '$hallId' order by recordDate asc,time asc"));
            foreach ($result['array'] as $array) {
                $payTr[] = [
                    $array['recordDate'],
                    $array['orderNo'],
                    $array['money'],
                    self::findStaff($array['payStid']),
                    $array['text'],
                ];
            }
            //按钮
            $button = [];
            $hall = query('dining_hall',"id = '$hallId'");
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                array(
                    array(
                        "<form name='detailForm'><div class='search' style='padding-left: 0'>".hidden(array('name'=>'hallId','value'=>$hallId)).hidden(array('name'=>'supplierName','value'=>$supplierName)).text(array("name" => "createTime", 'class'=>'text width300','laydate' => ['type' => 'date', 'range' => '~'], "title" => "日期-日期"))."<input type='button' onclick='searchMx()' class='searchSub' value='查询'></div></form>",
                    ),
                    array(
                        "<div class='space bg-light-grey'></div>"
                    ),
                    array(
                        '食堂名称'=>$hall['name'],
                        '供应商名称'=>$supplierName
                    ),
                ),
            ));
            $data['html'] .= $this->detailList([
                'title' => '采购明细',
                'html' => "<div id='purchaseMx'>".$this->listTable(array('tr' => $purchaseTr, 'showSort' => true))."</div>"
            ]);
            $data['html'] .= $this->detailList([
                'title' => '付款明细',
                'html' => "<div id='payMx'>".$this->listTable(array('tr' => $payTr, 'showSort' => true))."</div>"
            ]);
            $data['html'].=$this->detailJs();
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }
    public function detailJs(): string
    {
        return <<<eof
<script>
function searchMx(){
    $.post(root+'control/adIndex.html?cla=canteenPay&fun=getSearch',$("form[name='detailForm']").serialize(),function(res) {
        $("#purchaseMx").empty().append(res.purchaseMx);
        $("#payMx").empty().append(res.payMx);
    },'json')
}
</script>
eof;
    }
    public function getSearch(): bool|string
    {
        $hallId = $this->post('hallId');
        $supplierName= $this->post('supplierName');
        $purchaseWhere =$payWhere= '';
        if ($this->post('createTime')){
            $purchaseWhere .= self::timeComparison($this->post('createTime'),field: "b.purchaseDate");
            $payWhere.=self::timeComparison($this->post('createTime'),field: "recordDate");
        }
        $purchaseTr[] = ['日期', '单号', '类别', '产品名称', '数量', '单价('.static::$unit.')', '金额('.static::$unit.')', '备注'];
        $result = find(array('table' => 'canteen_detail as a join canteen as b on a.orderId = b.id', 'field'=>"a.*,b.orderNo,b.purchaseDate",'where' => "b.hallId = '$hallId' and a.supplierName = '$supplierName' {$purchaseWhere} order by a.list asc"));
        foreach ($result['array'] as $array) {
            $purchaseTr[] = [
                $array['purchaseDate'],
                $array['orderNo'],
                $array['type'],
                $array['materialName'],
                $array['num'],
                $array['price'],
                round($array['num']*$array['price']),
                $array['text'],
            ];
        }
        $json['purchaseMx'] = $this->listTable(array('tr' => $purchaseTr, 'showSort' => true));
        $payTr[] = ['日期', '单号', '付款金额('.static::$unit.')', '付款人','备注'];
        $result = find(array('table' => 'payment', 'where' => "targetId = '$supplierName' and hallId = '$hallId' {$payWhere} order by recordDate asc,time asc"));
        foreach ($result['array'] as $array) {
            $payTr[] = [
                $array['recordDate'],
                $array['orderNo'],
                $array['money'],
                self::findStaff($array['payStid']),
                $array['text'],
            ];
        }
        $json['payMx'] = $this->listTable(array('tr' => $payTr, 'showSort' => true));
        return json_encode($json,320);
    }

    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = [];
            }else{
                $sql = static::rGet(self::$stid.self::page . 'sql');
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $hall = query('dining_hall', "id = '$array[hallId]'");
                $payMoney = find(array('table'=>'payment','where'=>"targetId = '$array[supplierName]' and hallId = '$array[hallId]' and state = '已通过' and isPay = 1",'sum'=>"money"));
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '食堂名称'=>$hall['name'],
                            '供应商名称'=>$array['supplierName'],
                            '采购金额'=>round($array['buyMoney'],2),
                            '已付款金额'=>$payMoney,
                            '剩余未付金额'=>$array['buyMoney'] - $payMoney,
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = $this->control['name'] . "导出了采购付款统计";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, "采购付款统计.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'食堂名称',
                    'aliasName'=>'食堂名称',
                ],
                [
                    'columnName'=>'供应商名称',
                    'aliasName'=>'供应商名称',
                ],
                [
                    'columnName'=>'采购金额',
                    'aliasName'=>'采购金额',
                ],
                [
                    'columnName'=>'已付款金额',
                    'aliasName'=>'已付款金额',
                ],
                [
                    'columnName'=>'剩余未付金额',
                    'aliasName'=>'剩余未付金额',
                ],
            ]
        };
    }
}

